package persistence

import (
	"Data-API-MCP/backend/internal/domain/entity"
	"context"
	"database/sql"
	"fmt"
)

// MCPServiceRepository MCP服务仓库实现
type MCPServiceRepository struct {
	db *sql.DB
}

// NewMCPServiceRepository 创建MCP服务仓库
func NewMCPServiceRepository(db *sql.DB) *MCPServiceRepository {
	return &MCPServiceRepository{db: db}
}

// CreateService 创建服务
func (r *MCPServiceRepository) CreateService(ctx context.Context, service *entity.MCPService) error {
	query := `
		INSERT INTO mcp_services (
			id, name, type, host, port, status, config, description, sql, connection_id, created_at, updated_at, last_used_at, tags, is_active, is_system
		) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
	`
	_, err := r.db.ExecContext(ctx, query,
		service.ID,
		service.Name,
		service.Type,
		service.Host,
		service.Port,
		service.Status,
		service.Config,
		service.Description,
		service.SQL,
		service.ConnectionID,
		service.CreatedAt,
		service.UpdatedAt,
		service.LastUsedAt,
		service.Tags,
		service.IsActive,
		service.IsSystem,
	)
	return err
}

// GetService 获取服务
func (r *MCPServiceRepository) GetService(ctx context.Context, id int64) (*entity.MCPService, error) {
	query := `
		SELECT id, name, type, host, port, status, config, description, sql, connection_id, created_at, updated_at, last_used_at, tags, is_active, is_system
		FROM mcp_services
		WHERE id = ?
	`
	var service entity.MCPService
	err := r.db.QueryRowContext(ctx, query, id).Scan(
		&service.ID,
		&service.Name,
		&service.Type,
		&service.Host,
		&service.Port,
		&service.Status,
		&service.Config,
		&service.Description,
		&service.SQL,
		&service.ConnectionID,
		&service.CreatedAt,
		&service.UpdatedAt,
		&service.LastUsedAt,
		&service.Tags,
		&service.IsActive,
		&service.IsSystem,
	)
	if err != nil {
		return nil, fmt.Errorf("查询服务失败: %v", err)
	}
	return &service, nil
}

// ListServices 获取服务列表
func (r *MCPServiceRepository) ListServices(ctx context.Context) ([]*entity.MCPService, error) {
	query := `
		SELECT id, name, type, host, port, status, config, description, sql, connection_id, created_at, updated_at, last_used_at, tags, is_active, is_system
		FROM mcp_services
		ORDER BY created_at DESC
	`
	rows, err := r.db.QueryContext(ctx, query)
	if err != nil {
		return nil, fmt.Errorf("查询服务列表失败: %v", err)
	}
	defer rows.Close()

	services := make([]*entity.MCPService, 0)
	for rows.Next() {
		var service entity.MCPService
		if err := rows.Scan(
			&service.ID,
			&service.Name,
			&service.Type,
			&service.Host,
			&service.Port,
			&service.Status,
			&service.Config,
			&service.Description,
			&service.SQL,
			&service.ConnectionID,
			&service.CreatedAt,
			&service.UpdatedAt,
			&service.LastUsedAt,
			&service.Tags,
			&service.IsActive,
			&service.IsSystem,
		); err != nil {
			return nil, fmt.Errorf("扫描服务数据失败: %v", err)
		}
		services = append(services, &service)
	}
	return services, nil
}

// UpdateService 更新服务
func (r *MCPServiceRepository) UpdateService(ctx context.Context, service *entity.MCPService) error {
	query := `
		UPDATE mcp_services
		SET name = ?, type = ?, host = ?, port = ?, status = ?, config = ?, description = ?, sql = ?, connection_id = ?, updated_at = ?, last_used_at = ?, tags = ?, is_active = ?, is_system = ?
		WHERE id = ?
	`
	_, err := r.db.ExecContext(ctx, query,
		service.Name,
		service.Type,
		service.Host,
		service.Port,
		service.Status,
		service.Config,
		service.Description,
		service.SQL,
		service.ConnectionID,
		service.UpdatedAt,
		service.LastUsedAt,
		service.Tags,
		service.IsActive,
		service.IsSystem,
		service.ID,
	)
	return err
}

// DeleteService 删除服务
func (r *MCPServiceRepository) DeleteService(ctx context.Context, id int64) error {
	query := `DELETE FROM mcp_services WHERE id = ?`
	_, err := r.db.ExecContext(ctx, query, id)
	return err
}

// CreateServiceParam 创建服务参数
func (r *MCPServiceRepository) CreateServiceParam(ctx context.Context, param *entity.MCPServiceParam) error {
	query := `
		INSERT INTO mcp_service_params (
			id, service_id, name, type, required, description, default_value
		) VALUES (?, ?, ?, ?, ?, ?, ?)
	`
	_, err := r.db.ExecContext(ctx, query,
		param.ID,
		param.ServiceID,
		param.Name,
		param.Type,
		param.Required,
		param.Description,
		param.DefaultValue,
	)
	return err
}

// GetServiceParams 获取服务参数列表
func (r *MCPServiceRepository) GetServiceParams(ctx context.Context, serviceID string) ([]*entity.MCPServiceParam, error) {
	query := `
		SELECT id, service_id, name, type, required, description, default_value, created_at, updated_at
		FROM mcp_service_params
		WHERE service_id = ?
		ORDER BY created_at
	`
	rows, err := r.db.QueryContext(ctx, query, serviceID)
	if err != nil {
		return nil, fmt.Errorf("查询服务参数列表失败: %v", err)
	}
	defer rows.Close()

	params := make([]*entity.MCPServiceParam, 0)
	for rows.Next() {
		var param entity.MCPServiceParam
		if err := rows.Scan(
			&param.ID,
			&param.ServiceID,
			&param.Name,
			&param.Type,
			&param.Required,
			&param.Description,
			&param.DefaultValue,
			&param.CreatedAt,
			&param.UpdatedAt,
		); err != nil {
			return nil, fmt.Errorf("扫描服务参数数据失败: %v", err)
		}
		params = append(params, &param)
	}
	return params, nil
}

// UpdateServiceParam 更新服务参数
func (r *MCPServiceRepository) UpdateServiceParam(ctx context.Context, param *entity.MCPServiceParam) error {
	query := `
		UPDATE mcp_service_params
		SET name = ?, type = ?, required = ?, description = ?, default_value = ?
		WHERE id = ?
	`
	_, err := r.db.ExecContext(ctx, query,
		param.Name,
		param.Type,
		param.Required,
		param.Description,
		param.DefaultValue,
		param.ID,
	)
	return err
}

// DeleteServiceParam 删除服务参数
func (r *MCPServiceRepository) DeleteServiceParam(ctx context.Context, id string) error {
	query := `DELETE FROM mcp_service_params WHERE id = ?`
	_, err := r.db.ExecContext(ctx, query, id)
	return err
}

// CreateServiceVersion 创建服务版本
func (r *MCPServiceRepository) CreateServiceVersion(ctx context.Context, version *entity.MCPServiceVersion) error {
	query := `
		INSERT INTO mcp_service_versions (
			id, service_id, version, sql, parameters, description, is_active
		) VALUES (?, ?, ?, ?, ?, ?, ?)
	`
	_, err := r.db.ExecContext(ctx, query,
		version.ID,
		version.ServiceID,
		version.Version,
		version.SQL,
		version.Parameters,
		version.Description,
		version.IsActive,
	)
	return err
}

// GetServiceVersion 获取服务版本
func (r *MCPServiceRepository) GetServiceVersion(ctx context.Context, id string) (*entity.MCPServiceVersion, error) {
	query := `
		SELECT id, service_id, version, sql, parameters, description, is_active, created_at, updated_at
		FROM mcp_service_versions
		WHERE id = ?
	`
	var version entity.MCPServiceVersion
	err := r.db.QueryRowContext(ctx, query, id).Scan(
		&version.ID,
		&version.ServiceID,
		&version.Version,
		&version.SQL,
		&version.Parameters,
		&version.Description,
		&version.IsActive,
		&version.CreatedAt,
		&version.UpdatedAt,
	)
	if err != nil {
		return nil, fmt.Errorf("查询服务版本失败: %v", err)
	}
	return &version, nil
}

// GetServiceVersions 获取服务版本列表
func (r *MCPServiceRepository) GetServiceVersions(ctx context.Context, serviceID string) ([]*entity.MCPServiceVersion, error) {
	query := `
		SELECT id, service_id, version, sql, parameters, description, is_active, created_at, updated_at
		FROM mcp_service_versions
		WHERE service_id = ?
		ORDER BY created_at DESC
	`
	rows, err := r.db.QueryContext(ctx, query, serviceID)
	if err != nil {
		return nil, fmt.Errorf("查询服务版本列表失败: %v", err)
	}
	defer rows.Close()

	versions := make([]*entity.MCPServiceVersion, 0)
	for rows.Next() {
		var version entity.MCPServiceVersion
		if err := rows.Scan(
			&version.ID,
			&version.ServiceID,
			&version.Version,
			&version.SQL,
			&version.Parameters,
			&version.Description,
			&version.IsActive,
			&version.CreatedAt,
			&version.UpdatedAt,
		); err != nil {
			return nil, fmt.Errorf("扫描服务版本数据失败: %v", err)
		}
		versions = append(versions, &version)
	}
	return versions, nil
}

// UpdateServiceVersion 更新服务版本
func (r *MCPServiceRepository) UpdateServiceVersion(ctx context.Context, version *entity.MCPServiceVersion) error {
	query := `
		UPDATE mcp_service_versions
		SET version = ?, sql = ?, parameters = ?, description = ?, is_active = ?
		WHERE id = ?
	`
	_, err := r.db.ExecContext(ctx, query,
		version.Version,
		version.SQL,
		version.Parameters,
		version.Description,
		version.IsActive,
		version.ID,
	)
	return err
}

// DeleteServiceVersion 删除服务版本
func (r *MCPServiceRepository) DeleteServiceVersion(ctx context.Context, id string) error {
	query := `DELETE FROM mcp_service_versions WHERE id = ?`
	_, err := r.db.ExecContext(ctx, query, id)
	return err
}

// ActivateServiceVersion 激活服务版本
func (r *MCPServiceRepository) ActivateServiceVersion(ctx context.Context, serviceID, versionID string) error {
	tx, err := r.db.BeginTx(ctx, nil)
	if err != nil {
		return fmt.Errorf("开始事务失败: %v", err)
	}
	defer tx.Rollback()

	// 先将所有版本设置为非激活
	_, err = tx.ExecContext(ctx, `
		UPDATE mcp_service_versions
		SET is_active = false
		WHERE service_id = ?
	`, serviceID)
	if err != nil {
		return fmt.Errorf("更新版本状态失败: %v", err)
	}

	// 激活指定版本
	_, err = tx.ExecContext(ctx, `
		UPDATE mcp_service_versions
		SET is_active = true
		WHERE id = ? AND service_id = ?
	`, versionID, serviceID)
	if err != nil {
		return fmt.Errorf("激活版本失败: %v", err)
	}

	return tx.Commit()
}
